package softWareConstructPro;
//reference:  www.cnblogs.com/chen-lhx/p/5610678.html
import java.io.*;
import java.util.ArrayList;

import javax.swing.JTextField;
/*练习文件的组织形式
capacity(试题数量),maxKey(算式最大值),op_status(试题类型)
(第一条算式记录)left_op(左操作数),opt(操作符),right_op(右操作数),answer(用户作答的答案,用以核对结果,没有则不填)
(第二条算式记录)
...
(第capacity条算式记录)
 */
public class ExerciseSaver {//练习保存类
	private final String path = "src/allExercise";//练习文件的保存路径
	public ArrayList<String> fileList = new ArrayList<>();//练习文件的字符串列表(可变数组)
	private Exercise myex;//用来导出/导入练习用的Exercise类
	private ArrayList<JTextField> list;//用来导出/导入练习答案(用户作答)的JTextField可变数组
	public ExerciseSaver() {//默认构造函数
		this.myex = null;
		this.list = null;
	}
	public ExerciseSaver(Exercise neoEx, ArrayList<JTextField> neoList) {//重载构造函数,将gui中接收到的信息(myex,用户作答用的JTextFiled组件)传入练习保存类中
		this.myex = neoEx;
		this.list = neoList;
	}
	public void setExercise(Exercise neoEx) {
		this.myex = neoEx;
	}
	public void setJTFList(ArrayList<JTextField> neoList) {
		this.list = neoList;
	}
	public void loadExercise(String fileName) {//加载练习题函数,fileName指所有练习题中选中的题的名字
		File myfile = new File(""+path+"/"+fileName);//拼接成具体的相对(工程文件的)路径
		FileReader fr = null;//将文件阅读类初始为空
		
		try {//尝试以下操作
			fr = new FileReader(myfile);
			BufferedReader br = new BufferedReader(fr);
			String temp = null;
			temp = br.readLine();//读取文件的第一行,给Exercise类的capacity,maxKey,op_status赋值
			String[] numStr = temp.split(",");
			myex.setCapacity(Integer.parseInt(numStr[0]));
			myex.setMaxKey(Integer.parseInt(numStr[1]));
			myex.setOp(Integer.parseInt(numStr[2]));
			for(int i = 0; i < myex.getCapacity(); ++i) {//得到capacity(试题数量),进行循环读入
				temp = br.readLine();
				String[] tStr = temp.split(",");
				BinaryOperation bot = new BinaryOperation(Integer.parseInt(tStr[0]), Integer.parseInt(tStr[1]), Integer.parseInt(tStr[2]));
				JTextField jtf = new JTextField(5);
				if(tStr.length == 4) {//如果算式记录提取的字符串数组长度为4,则证明用户填了答案
					jtf.setText(tStr[3]);
				}
				else {//长度为3,用户没有填答案,所以JTextField初始化为"(空)"
					jtf.setText("");
				}
				jtf.setEditable(true);
				if(myex.insertBO(bot) != true) {//添加算式函数为true则可以继续运行,false则说明在异常的时刻调用了loadExercise函数
					System.out.println(i + " load exercise failed");
					break;
				}
				list.add(jtf);//将生成的JTextField组件加入到它的动态数组中
			}
			br.close();//关闭缓存读取类
		}catch(Exception e) {//接收try返回的信息
			System.out.println(e);
		}
		finally {//处理没有关闭的文件阅读类
			if(fr != null) {
				try {
					fr.close();
				}catch(IOException e) {
					throw new RuntimeException("Close Failed");
				}
			}
		}
	}
	public void readAllFileName() {//获取所有习题文件名函数
		//add sth to fileList
		/*
		 File file = new File(path);   
        File[] array = file.listFiles();
        array[i].isFile()  
		 
		 */
		this.fileList.clear();//首先清空ExericseSaver类的文件表变长字符串记录
		File file = new File(path);
		File[] array = file.listFiles();
		int len = array.length;
		if(len != 0) {
			for(int i = 0; i < len; ++i) {
				String t = array[i].getName();//.split(".")[0]
				//System.out.println(t);
				this.fileList.add(t);
			}
		}
	}
	public boolean deleteExerciseFile(String fileName) {//删除练习文件函数
		boolean check = true;
		File myfile = new File(""+path+"/"+fileName);
		if(myfile.exists() == true) {//如果文件存在,执行文件类的删除函数
			myfile.delete();
			//System.out.println(myfile.getName() + " Delete success!");//some tip
		}
		else {//不存在,报错误
			check = false;
			//System.out.println(myfile.getName() + "do not exist! Delete failed!");//need to be updated to JOptionPane
		}
		return check;
	}
	public boolean createExerciseFile(String fileName) {//新建练习题文件函数,本工程保存文件名统一为".txt"
		boolean check = true;
		File myfile = new File(""+path+"/"+fileName);//.txt
		if(myfile.exists() == true) {//检验文件是否存在,文件存在,则提示文件存在,无法储存文件
			check = false;
			//System.out.println(fileName + " was exist!");
		}
		else//文件不存在,开始执行存储文件代码
		{
			try {
				myfile.createNewFile();//文件类的创建文件函数
				FileWriter fw = new FileWriter(myfile);
				BufferedWriter bw = new BufferedWriter(fw);
				String settingStr = "" + myex.getCapacity()+","+myex.getMaxKey()+","+myex.getOp();
				bw.write(settingStr);
				bw.newLine();
				bw.flush();//每缓存一行数据就要执行一次写入
				
				for(int i = 0; i < myex.getCapacity(); ++i) {
					BinaryOperation bot = myex.getBO(i);
					if(bot != null) {
						settingStr = "" + bot.getLeft_op() + "," + bot.getOpt() + "," + bot.getRight_op() + "," + this.list.get(i).getText();
						//System.out.println(settingStr);//
						bw.write(settingStr);
						bw.newLine();
						bw.flush();
					}
					else {//设置判断防止读取的Exercise类的练习题越界,越界则报出错误,停止写入练习题,删除练习题
						//System.out.println("index out of range, write file failed!");
						myfile.delete();
						check = false;
						break;
					}
				}
				//this.myex.afterUsed();
				//this.list.clear();
				fw.close();
				bw.close();//关闭文件文件写入和缓存写入类
				//System.out.println(fileName + " create success.");
			}catch(Exception e) {
				System.out.println(e);
			}
			//
			
			
		}
		return check;
	}
	public String toString() {
		String ans = "";
		ans += myex.getCapacity();
		ans += " printed.\n";
		myex.setUsing();
		for(int i = 0; i < myex.getCapacity(); ++i) {
			System.out.println(myex.getBO(i) + list.get(i).getText());
		}
		myex.afterUsed();
		return ans;
	}
}
